package com.hmall.gateway.filters;

import com.hmall.common.exception.UnauthorizedException;
import com.hmall.common.utils.CollUtils;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
//@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;

    private final JwtTool jwtTool;


    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    public AuthGlobalFilter(AuthProperties authProperties, JwtTool jwtTool) {
        this.authProperties = authProperties;
        this.jwtTool = jwtTool;
    }




    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取请求头信息
        ServerHttpRequest request = exchange.getRequest();
        RequestPath path = request.getPath();
        // 2.判断请求路径是否需要放行
        if (isAuthorized(path)) {
            return chain.filter(exchange);
        }
        // 3.获取请求头的token信息
        String token = null;
        List<String> authorization = request.getHeaders().get("Authorization");
        if (authorization != null && !CollUtils.isEmpty(authorization)) {
            token = authorization.get(0);
        }
        // 4.判断token是否合法，解析token获取用户信息
        Long userId = null;
        try {
            userId = jwtTool.parseToken(token);
        } catch (UnauthorizedException e) {
            // 如果token无效则拦截
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //  5.传递用户信息
//        System.out.println("userId = " + userId);
        String userInfo = userId.toString();
        ServerWebExchange swe = exchange.mutate().request(builder -> builder.header("user-info", userInfo))
                .build();
        // 6.放行
        return chain.filter(swe);
    }

    /**
     * 判断请求路径是否需要放行
     *
     * @param path
     * @return
     */
    private boolean isAuthorized(RequestPath path) {
        List<String> excludePatterns = authProperties.getExcludePaths();
        for (String excludePattern : excludePatterns) {
            if (antPathMatcher.match(excludePattern, path.toString())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
